# Copyright (C) 2010 Punyashloka Biswal, Smita Gopinath, Drew Hotson.

import csv, sys
import os, os.path
from itertools import combinations

experiments = [
    (os.path.splitext(os.path.basename(fn))[0], float(sig), float(trend),
     dict(((x, y), float(c)) for (x, y, c) in
          (row[-3:] for row in csv.reader(open(fn, 'U')))))
    for (fn, sig, trend) in csv.reader(open('thresholds.csv', 'U'))]

if not os.path.exists('out'):
    os.mkdir('out')

for ((f1, s1, t1, d1), (f2, s2, t2, d2)) in combinations(experiments, 2):
    outfile = open('out/pairs-%s-%s.csv' % (f1, f2), 'wb')
    out = csv.writer(outfile)
    for k in sorted(set(d1) & set(d2)):
        if (d1[k] >= s1 and d2[k] >= t2) or (d1[k] >= t1 and d2[k] >= s2):
            out.writerow(k + (1,))
        elif (d1[k] <= -s1 and d2[k] <= -t2) or (d1[k] <= -t1 and d2[k] <= -s2):
            out.writerow(k + (-1,))
    outfile.close()

outfile = open('out/common.csv', 'wb')
out = csv.writer(outfile)
for k in sorted(experiments[0][3]):
    if any(k not in d for (f, s, t, d) in experiments):
        continue
    if all(d[k] >= t for (f, s, t, d) in experiments) and any(d[k] >= s for (f, s, t, d) in experiments):
        out.writerow(k + (1,))
    elif all(d[k] <= -t for (f, s, t, d) in experiments) and any(d[k] <= -s for (f, s, t, d) in experiments):
        out.writerow(k + (-1,))
outfile.close()
